package com.test.datasource.dsconfig;

import com.test.datasource.DataSourceDefine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import static com.test.datasource.DataSourceDefine.DATASOURCE_PARK;

/**
 * @author meiliangdeng
 */
@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPark",
        transactionManagerRef = "transactionManagerPark",
        basePackages = "com.test.dao.order")
public class A0ParkDataSourceConfigurer {

    private final DataSource parkSource;

    private final JpaProperties jpaProperties;

    @Autowired
    public A0ParkDataSourceConfigurer(
            @Qualifier(DataSourceDefine.DATASOURCE_PARK) DataSource parkSource,
            JpaProperties jpaProperties) {
        this.parkSource = parkSource;
        this.jpaProperties = jpaProperties;
    }

    @Primary
    @Bean(name = "entityManagerPark")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPark(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactoryPark")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPark(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(parkSource)
                .properties(jpaProperties.getProperties())
                .packages("com.test.dao.park.entity")
                .persistenceUnit("parkPersistenceUnit")
                .build();
    }

    @Primary
    @Bean(name = "transactionManagerPark")
    public PlatformTransactionManager transactionManagerPark(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPark(builder).getObject());
    }

}
